package com.zmx.common.common.web.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description: Controller控制器返回数据前统一处理
 * @ClassName: RestResponseBodyAdvice
 * @Author zhaomxr
 * @Date 2021-10-09 16:32
 */
@RestControllerAdvice
public class RestResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        boolean classHasAnnotation = AnnotationUtils.findAnnotation(methodParameter.getDeclaringClass(), WrappedResponse.class) != null;
        boolean methodHasAnnotation = methodParameter.hasMethodAnnotation(WrappedResponse.class);
        return classHasAnnotation || methodHasAnnotation;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body instanceof String) {
            return objectMapper.writeValueAsString(body);
        } else if (body instanceof ResponseResult) {
            return body;
        }
        return ResponseResult.success(body);
    }
}
